package com.dkm.service.impl;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dkm.entity.Module;
import com.dkm.entity.Permission;
import com.dkm.entity.Role;
import com.dkm.repository.PermissionRepository;
import com.dkm.repository.RoleRepository;
import com.dkm.service.PermissionService;
import com.dkm.util.TreeNode;

@Service
public class PermissionServiceImpl implements PermissionService {
	//注入角色业务层
	@Autowired
	private RoleRepository roleRepository;
	//注入权限业务层
	@Autowired
	private PermissionRepository permissionRepository;
	@Override
	public List<Permission> getAllPermissions() {
		// TODO Auto-generated method stub
		return permissionRepository.findAll();
	}
	@Override
	public List<TreeNode> getCheckedModulePermissionTreeByRole(String role_id, List<TreeNode> treeNodes) {
		//获取角色信息
		Role role=roleRepository.findById(role_id).get();
		//如果角色为空
		if(role!=null) {
			//获取用户的模块和角色信息
			List<Module> modules=role.getModules();
			List<Permission> permissions=role.getPermissions();
			//创建节点信息
			TreeNode t=null;
			//遍历用户的模块信息
			if(modules!=null) {
				for (Module module : modules) {
					t=new TreeNode();
					t.setId(module.getModule_id());
					t.setField("module");
					//查找节点设置选中
					this.checkedTreeNode(t, treeNodes);
				}
			}
			//遍历用户的权限信息
			if(modules!=null) {
				for (Permission permission : permissions) {
					t=new TreeNode();
					t.setId(permission.getPermission_id());
					t.setField("permission");
					//查找节点设置选中
					this.checkedTreeNode(t, treeNodes);
				}
			}
		}
		
		return treeNodes;
	}
	@Override
	public List<TreeNode> checkedTreeNode(TreeNode treeNode, List<TreeNode> treeNodes) {
		//遍历树结构
		for (TreeNode item : treeNodes) {
			
			//如果当前遍历数据中存在节点
			if(item.getId().equals(treeNode.getId())&&item.getField().equals(treeNode.getField())) {
				if(item.getChildren()==null) {
					//设置节点选中
					item.setChecked(true);
				}
			}else {
				//不存在查找子集
				if(item.getChildren()!=null) {
					
					this.checkedTreeNode(treeNode, item.getChildren());
				}
			}
			
		}
		return treeNodes;
	}
	@Override
	public Optional<Permission> getPermissionById(String permission_id) {
		
		return permissionRepository.findById(permission_id);
	}

}
